package action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.Helper;
import table.Team;
import table.TeamHandle;
import table.User;

/**
 * 用于改变小组信息的控制器
 */
@WebServlet("/TeamInfoModify")
public class TeamInfoModify extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TeamInfoModify() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 使用get访问该页无效
		response.getWriter().append("Please use POST method!");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 用户登录有效性验证段
		User user = (User) request.getSession().getAttribute("user");
		if(user == null){
			request.getRequestDispatcher("index.jsp").forward(request, response);
			return;
		}
		
		String old_id = user.getId();
		if(old_id == null) {
			return;
		}
		
		System.out.println("new ID: " + Helper.getString(request.getParameter("txt_account")));
		System.out.println("new Name: " + Helper.getString(request.getParameter("txt_name")));
		System.out.println("new Team ID:" + Helper.getString(request.getParameter("txt_team")));
		String teamName = Helper.getString(request.getParameter("txt_team_name_modify"));
		String teamInfo = Helper.getString(request.getParameter("txt_team_intro_modify"));
		
		Team newTeam = new Team();
		newTeam.setId(user.getTeamid());
		newTeam.setName(teamName);
		newTeam.setInfo(teamInfo);
		TeamHandle handle = new TeamHandle();
		if(handle.updateToDB(newTeam.getId(), newTeam)) {
			// 如果修改成功则返回之前修改页面，并弹出修改成功
			response.getWriter().println("<script>window.location.href='user_team_info.jsp';alert('Successfully modified!');</script>");
		}else {
			// 如果修改失败则返回之前修改页面，并弹出修改失败
			response.getWriter().println("<script>window.location.href='user_team_info_modify.jsp';alert('Fail to modify!');</script>");
		}
	}

}
